package com.cysyz.mylib.web.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;

public class IPUtil {
	static String apiUrl="http://ip.taobao.com/service/getIpInfo.php?ip=";
	
	public static String getCityByIP(String ip){
		String defaultcity = "北京";
		try {
			URL url = new URL(apiUrl+ip);
			
		    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		    InputStream inputStream = httpCon.getInputStream();
		    InputStreamReader inputReader = new InputStreamReader(inputStream,"gbk");
		    BufferedReader bufferReader = new BufferedReader(inputReader);
		    String inputLine = null;  
	        StringBuffer sb = new StringBuffer();
	        while ((inputLine = bufferReader.readLine()) != null) {   
	            sb.append(inputLine);
	        }   
	        bufferReader.close();  
	        inputReader.close();
	        inputStream.close();
	        String json=sb.toString();
	        JSONObject jsonObject=new JSONObject(json);
	        int code=jsonObject.getInt("code");
	        if(code==1){
	        	return defaultcity;
	        }else{
	        	JSONObject data=jsonObject.getJSONObject("data");
	        	String city=data.getString("city");
	        	return city;
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
        return defaultcity;
	}
	
	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
//	public static void main(String[] args) {
//		String city=IPUtil.getCityByIP("210.75.225.254");
//		System.out.println(city.equals("北京市"));
//	}
}
